<template>
  <view class="shoppingCart">
    <view class="welfareMall" v-show="goods && goods.length>0">
      <view class="allWelfare">
        <checkbox-group @change='allWelfare'>
          <checkbox value="cb" class="checkedwel" color="#FFFFFF" :checked="allwelfareCheck"/>
        </checkbox-group>
        <text class="welfareTitle">{{welfaretitle}}</text>
        <image :src="$store.state.imgBaseUrl + '/goodDetail/del.png'" @click="delshopping"></image>
      </view>
      <view class="welfareContent" v-for="(item,index) in goods" :key='index'>
        <checkbox-group @change='selectwelfare(index)'>
          <checkbox value="welf" color="#FFFFFF" :checked="item.welfarecheck"/>
        </checkbox-group>
        <image :src="item.herf" class="image"></image>
        <view class="content">
          <text class="content_a">{{item.productName}}</text>
          <text class="content_b">{{item.skuStr.toString()}}</text>
          <view class="content_c">
            <text class="c_icon">¥</text>
            <text class="c_moneny">{{item.price | toFixed(2)}}</text>
            <view class="c_num">
              <image :src="$store.state.imgBaseUrl + '/goodDetail/dismin.png'" class="num_ched" v-show="item.quantity == 1"></image>
              <image :src="$store.state.imgBaseUrl + '/goodDetail/minus.png'" class="num_ch" v-show="item.quantity > 1" @click="changeNum(index, 'cut')"></image>
              <text class="num_show">{{item.quantity}}</text>
              <image :src="$store.state.imgBaseUrl + '/goodDetail/plus.png'" class="num_ch" @click="changeNum(index, 'add')"></image>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="loading" v-if="goods.length != 0">{{loadingText}}</view>
    <block v-if="goods.length == 0">
      <view class="goot-empty-ml">
        <image :src="$store.state.imgBaseUrl + '/goodDetail/empty-shop.png'"></image>
        <view class="text1">您的购物车空空如也~</view>
        <view class="text2">快速返回商城~</view>
      </view>
      <view class="good-footer-ml">
        <button type="primary" class="sub-btn cur" plain="true" @click="gotoShopping">继续采购</button>
      </view>
    </block>
    <view class="shoppingFooter" v-if="goods && goods.length > 0">
      <view class="footer_left">
        <view class="left_a">
          <text class="a_combined">合计:</text>
          <text class="a_mey">¥</text>
          <text class="a_moneny">{{totalPrice | toFixed(2)}}</text>
        </view>
      </view>
      <view class="footer_right">
        <text @click="toBuyshop">去结算({{totalNum}})</text>
      </view>
    </view> 
    <common-pop :baseInfo="commonPopInfo" @cancelPop="cancelComPop" @doSure="delectCartGoods"></common-pop>
  </view>
</template>
<script>
import { queryCar, deleteCart, changeCart } from '@/service/purchaseShop/goodsCar.service.js';
import { saveCart } from '@/service/purchaseShop/goodsDetail.service.js';
import commonPop from '@/components/common-pop/index.vue'
var _self;
export default {
  components: {commonPop},
  data() {
    return {
      allwelfareCheck:false,
      arraychecked: [],
      allexchangeCheck:false,
      exchangechecked: [],
      showdisable:false,
      totalPrice:0,
      totalNum:0,
      goodsCartData:'',
      exchangetitle:'',
      welfaretitle:'',
      welfare:{},
      exchange:{},
      goods: [],
      loadingText: '加载中...',
      pages: {
        size: 10,
        total: 0,
        current: 1,
        noList: true
      },
      loadingFlag: false,
      commonPopInfo: {
        title: '确认删除购物车吗？',
        cancel: '取消',
        sure: '确定',
        show: false
      }
    };
  },
  onLoad () {
    _self= this;
    this.getshopCartlist()
  },
  onReachBottom:function() {
    // 页面滚动到底部的事件
    _self.getMoreDatas();
  },
  methods:{
    cancelComPop () {
      this.commonPopInfo.show = false;
    },
    gotoShopping () {
      uni.navigateTo({
        url:'/pages/purchaseShop/index'
      })
    },
    getMoreDatas () {
      if (!this.loadingFlag) {
        return false;
      }
      this.pages.current++;
      this.getshopCartlist();
    },
    // 查询购物车
    getshopCartlist () {
      this.loadingText = '加载中...';
      uni.showNavigationBarLoading(); // 在当前页面显示导航条加载动画
      let that = this;
      let params = {
        size: this.pages.size,
        current: this.pages.current
      }
      queryCar(params, (res) => {
        if (res.status === 0) {
          if (res.data.records.length == 0 && this.goods.length == 0) {
            this.loadingFlag = false;
            uni.hideNavigationBarLoading();
            this.loadingText = '暂无数据';
            return false;
          }
          let typeList = res.data.records;
          typeList.map(i =>{
            if(i.id == '1'){
              // this.welfare = i
              this.welfaretitle = i.type;
              this.goods.push(...i.cartVoList);
              this.goods.map(index =>{
                if (this.allwelfareCheck) {
                  index.welfarecheck = true;
                  this.getTotal();
                } else {
                  if (!index.welfarecheck) {
                    index.welfarecheck = false
                  }
                }
              })
            }
          })
          if (this.goods.length == res.data.total) {
            this.loadingFlag = false;
            this.loadingText = '已加载全部'
          } else {
            this.loadingText = '加载更多';
            this.loadingFlag = true;
          }
          uni.hideNavigationBarLoading();
          uni.stopPullDownRefresh();
        }
      })
    },
    // 加载更多
    getMoreList () {
      let curGoodsCartDataLength = 0;
      curGoodsCartDataLength += this.welfare.cartVoList && this.welfare.cartVoList.length
      curGoodsCartDataLength += this.exchange.cartVoList && this.exchange.cartVoList.length
      if (Number(this.pages.total) === Number(curGoodsCartDataLength)) {
        this.pages.noList = false
        return
      }
      this.pages.current++
      this.getshopCartlist()
    },
    allWelfare (e) {
      // 判断全选还是全不选
      var arraylist = [];
      if (this.allwelfareCheck) {
        for (var i = 0; i < this.goods.length; i++) {
          this.goods[i].welfarecheck = false;
        }
        this.allwelfareCheck = false
      } else {
        for (var i = 0; i < this.goods.length; i++) {
          arraylist.push(this.goods[i]);
          this.goods[i].welfarecheck = true;
        }
        this.allwelfareCheck = true
        this.arraychecked = arraylist;
      }
      this.getTotal()
    },
    getTotal() {
      // 计算总价格
      this.totalPrice = 0;
      this.totalNum = 0;
      for (var i = 0; i < this.goods.length; i++) {
        var _d = this.goods[i]
        if (_d.welfarecheck) {
          this.totalPrice += _d['price'] * _d['quantity']
          this.totalNum +=_d['quantity']
        }
      }
    },
    selectwelfare (index) {
      // 单个商品的选择和取消
      if (this.goods[index].welfarecheck == true) {
        var obj = this.goods[index];
        obj.welfarecheck = !obj.welfarecheck;
        this.$set(this.goods, index, obj);
      } else {
        var obj = this.goods[index];
        obj.welfarecheck = !obj.welfarecheck;
        this.$set(this.goods, index, obj);
      }
      let arraylist = [];
      let arraychecked = [];
      for (var i = 0; i < this.goods.length; i++) {
        if (this.goods[i].welfarecheck == false) {
          arraylist.push(this.goods[i]);
        } else if (this.goods[i].welfarecheck == true) {
          arraychecked.push(this.goods[i]);
        }
      }
      // 判断是否全部勾选
      if (arraylist.length !== this.goods.length) {
        this.allwelfareCheck = false
      }
      if (arraychecked.length === this.goods.length) {
        this.allwelfareCheck = true
      }
      this.arraychecked = arraychecked;
      this.getTotal();
    },
    delshopping () {
      let ids=[];
      let delectArr = JSON.parse(JSON.stringify(this.goods)); // 记录删除后的数组
      for (let i = delectArr.length-1; i>=0; i--) {
        let _d = delectArr[i];
        if (_d.welfarecheck) {
          ids.push(delectArr[i].id);
          delectArr.splice(i, 1);
        }
      }
      if (ids.length ==  0) {
        uni.showToast({
          title: '请选择商品',
          icon: 'none'
        });
        return false;
      }
      this.commonPopInfo.show = true;
    },
    delectCartGoods () {
      let ids=[];
      let delectArr = JSON.parse(JSON.stringify(this.goods)); // 记录删除后的数组
      for (let i = delectArr.length-1; i>=0; i--) {
        let _d = delectArr[i];
        if (_d.welfarecheck) {
          ids.push(delectArr[i].id);
          delectArr.splice(i, 1);
        }
      }
      let params = {
        ids: ids.join(',')
      }
      deleteCart(params, (res) => {
        if (res.status == 0) {
          this.goods = delectArr; // 删除成功后重新给goods数组赋值给删除后的数组
          uni.showToast({
            title: '已删除',
            icon: 'none'
          });
          if (this.goods.length == 0) {
            this.loadingFlag = false;
            this.loadingText = '暂无数据';
          }
          this.commonPopInfo.show = false;
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none'
          });
        }
        this.getTotal();
      })
    },
    // 修改商品数量
    changeNum (index, type) {
      let beforeNum =this.goods[index].quantity; // 记录改变之前的数量
      let afterNum = null;
      if (type == 'add') {
        this.goods[index].quantity++;
        afterNum =this.goods[index].quantity; // 记录改变之后的数量
      } else {
        if (this.goods[index].quantity <= 1) return;
        this.goods[index].quantity--;
        afterNum =this.goods[index].quantity; // 记录改变之后的数量
      }
      let params = {
        id: this.goods[index].id,
        productSkuId: this.goods[index].productSkuId,
        quantity: afterNum,
        productId: this.goods[index].productId
      }
      changeCart(params, (res) => { // 修改数量的接口
        if (!res.status == 0) {
          this.goods[index].quantity = beforeNum;
          uni.showToast({
            title: res.msg,
            icon: 'none'
          }); 
        }
      })
      this.getTotal(); //计算总价和数量
    },
    // 结算商品
    toBuyshop () {
      let sureBuy = []
      let welfnum = '';
      for (var i = 0; i < this.goods.length; i++) {
        if(this.goods[i].welfarecheck){
          welfnum = true
          // sureBuy.push(this.goods[i])
          sureBuy.push(this.goods[i].id)
        }
      }
      uni.setStorage({
        key: 'orderCarNub',
        data: sureBuy.join(',')
      });
      console.log(sureBuy)
      if(welfnum){
        uni.navigateTo({
          url:'/pages/purchaseShop/goodsSureOrder?isCartBy=1'
        })
      }else{
        uni.showToast({
          title: '您还没有选择商品哦~',
          icon:'none',
          duration: 3000
        });
      }
    }
  }
}
</script>

<style scoped lang="scss">
  .loading {
    text-align: center;
    color: #666666;
    font-size: 28rpx;
  }
  .shoppingCart{
    padding-top: 20rpx;
    padding-bottom: 200rpx;
  }
  .welfareMall{
    width: 100%;
    background:rgba(255,255,255,1);
    box-shadow:0px 0px 30rpx 0rpx rgba(0,0,0,0.05);
    border-radius:8rpx;
    margin-bottom: 20rpx;
  }
  .exchangeMall{
    width: 100%;
    background:rgba(255,255,255,1);
    box-shadow:0px 0px 30rpx 0rpx rgba(0,0,0,0.05);
    border-radius:8rpx;
  }
  .allWelfare{
    height: 104rpx;
    line-height: 104rpx;
    margin: 0 36rpx;
    position: relative;
  }
  .disable_d{
    position: absolute;
    width:100rpx;
    height:200rpx;
    left: 0;
    background:rgba(255,255,255,1);
    opacity: 0;
  }
  .disable_c{
    position: absolute;
    width:100rpx;
    height:100rpx;
    left: 0;
    background:rgba(255,255,255,1);
    opacity: 0;
  }
  .disable_a{
    position: absolute;
    width:100rpx;
    height:100rpx;
    left: 0;
    background:rgba(255,255,255,1);
    opacity: 0;
  }
  .allWelfare checkbox-group{
    display: inline-block;
  }
  .welfareTitle{
    display: inline-block;
    height:40rpx;
    font-size:28rpx;
    font-family:PingFangSC-Regular,PingFang SC;
    font-weight:400;
    color:rgba(51,51,51,1);
    line-height:40rpx;
    margin-left: 32rpx;
    vertical-align: middle;
  }
  .allWelfare image{
    float: right;
    width:44rpx;
    height:44rpx;
    margin-top: 35rpx;
  }
  .welfareContent{
    height: 172rpx;
    margin: 2rpx 0rpx 0 36rpx;
    padding-bottom: 42rpx;
    position: relative;
  }
  .disable_b{
    position: absolute;
    width:100rpx;
    height:200rpx;
    left: 0;
    background:rgba(255,255,255,1);
    opacity: 0;
  }
  .welfareContent .image{
    width:172rpx;
    height:172rpx;
    line-height: 172rpx;
    margin-left: 32rpx;
  }
  .welfareContent checkbox-group{
    display: inline-block;
    vertical-align: top;
    margin-top: 64rpx;
  }
  .welfareContent .content{
    margin-left: 14rpx;
    display: inline-block;
    vertical-align: top;
  }
  .content .content_a{
    width:410rpx;
    font-size:26rpx;
    display: inline-block;
    font-family:PingFangSC-Regular,PingFang SC;
    font-weight:400;
    color:rgba(51,51,51,1);
    line-height:36rpx;
    display: -webkit-box;
    overflow: hidden;
    text-overflow: ellipsis;
    word-wrap: break-word;
    white-space: normal !important;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
   /deep/  uni-checkbox .uni-checkbox-input{
     width:36rpx;
     height:36rpx;
     background:rgba(255,255,255,1);
     border-radius:90rpx;
     border:2rpx solid rgba(51,51,51,1);
   }
   /deep/ uni-checkbox .uni-checkbox-input.uni-checkbox-input-checked{
     width:36rpx;
     height:36rpx;
     background:rgba(205,67,57,1);
     border-radius: 50%;
     border:2rpx solid rgba(205,67,57,1);
   }
   /deep/ uni-checkbox .uni-checkbox-input.uni-checkbox-input-checked:before{
     font-size: 34rpx;
   }
   checkbox .wx-checkbox-input{
     width:36rpx;
     height:36rpx;
     background:rgba(255,255,255,1);
     border-radius:90rpx;
     border:2rpx solid rgba(51,51,51,1);
   }
   /* 选中后的 背景样式 （红色背景 无边框 可根据UI需求自己修改） */
   checkbox .wx-checkbox-input.wx-checkbox-input-checked{
     width:36rpx;
     height:36rpx;
     background:rgba(205,67,57,1);
     border-radius: 50%;
     border:2rpx solid rgba(205,67,57,1);
   }
   /* 选中后的 对勾样式 （白色对勾 可根据UI需求自己修改） */
   checkbox .wx-checkbox-input.wx-checkbox-input-checked::before{
      font-size: 34rpx;
   }
  .content_b{
    display: inline-block;
    min-width:60rpx;
    padding: 0 10rpx;
    height:32rpx;
    margin-top: 8rpx;
    background:rgba(239,239,239,1);
    border-radius:16rpx;
    font-size:20rpx;
    font-family:PingFangSC-Regular,PingFang SC;
    font-weight:400;
    color:rgba(51,51,51,1);
    line-height:32rpx;
    text-align: center;
  }
  .content_c{
    font-size:20rpx;
    margin-top: 20rpx;
    font-family:PingFangSC-Medium,PingFang SC;
    font-weight:500;
    color:rgba(205,67,57,1);
  }
  .content_c .c_moneny{
    font-size:28rpx;
    line-height: 36rpx;
  }
  .content_c .c_num{
    float: right;
  }
  .c_num .num_ch{
    width:28rpx;
    height:30rpx;
    font-size:30rpx;
    font-family:PingFangSC-Medium,PingFang SC;
    font-weight:500;
    color:rgba(51,51,51,1);
    vertical-align: middle;
  }
  .c_num .num_ched{
    width:24rpx;
    height:30rpx;
    font-size:30rpx;
    font-family:PingFangSC-Medium,PingFang SC;
    font-weight:500;
    margin-right: 6rpx;
    color:rgba(51,51,51,1);
    vertical-align: middle;
  }
  .c_num .num_show{
    display: inline-block;
    text-align: center;
    width:60rpx;
    height:36rpx;
    line-height: 36rpx;
    background:rgba(245,245,245,1);
    border-radius:4rpx;
    vertical-align: middle;
    margin-left: 8rpx;
    color:rgba(51,51,51,1);
    margin-right: 8rpx;
  }
  .shoppingFooter{
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height:120rpx;
    background:rgba(255,255,255,1);
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
  .footer_left{
    margin-right: 20rpx;
  }
  .footer_left .left_a .a_combined{
    width:72rpx;
    height:34rpx;
    font-size:24rpx;
    vertical-align: text-top;
    font-family:PingFangSC-Regular,PingFang SC;
    font-weight:400;
    color:rgba(51,51,51,1);
    line-height:34rpx;
    margin-right: 12rpx;
  }
  .left_a{
    font-size:28rpx;
    font-family:PingFangSC-Medium,PingFang SC;
    font-weight:500;
    color:rgba(205,67,57,1);
  }
  .left_a .a_moneny{
    font-size:36rpx;
  }
  .left_b{
    width:106rpx;
    height:28rpx;
    font-size:20rpx;
    font-family:PingFangSC-Light,PingFang SC;
    font-weight:300;
    color:rgba(153,153,153,1);
    line-height:28rpx;
  }
  
  .footer_right text{
    display: inline-block;
    width:252rpx;
    height:88rpx;
    background: #434343;
    border-radius:44rpx;
    font-size:28rpx;
    font-family:PingFangSC-Medium,PingFang SC;
    font-weight:500;
    color: #F6DA99;
    line-height:88rpx;
    text-align: center;
    margin-right: 26rpx;
  }
  .load-more {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 80rpx;
    color: #333333;
    font-size: 26rpx;
    background: #FAFAFA;
  }
</style>
